package com.rocching.easychat.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.ActivityResultRegistry;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.rocching.easychat.MainActivity;
import com.rocching.easychat.R;
import com.rocching.easychat.adapter.FriendListExpandableListAdapter;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.ViewClickListener;
import com.rocching.easychat.model.FriendListModel;
import com.rocching.easychat.model.FriendModel;
import com.rocching.easychat.model.GroupFriendModel;
import com.rocching.easychat.model.UserModel;
import com.rocching.easychat.service.UserService;
import com.rocching.easychat.util.AppUtil;
import com.rocching.easychat.util.JsonUtil;
import com.rocching.easychat.util.StringUtil;

import java.util.List;
import java.util.Objects;

import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

public class FriendListFragment extends Fragment {
    private final String TAG = FriendListFragment.class.getName();

    private boolean initList = false;
    private ExpandableListView friendList;
    private FriendListModel data;
    private boolean hasInitData = false;
    private ActivityResultLauncher<Intent> launcher;

    public FriendListFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initLauncher();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_friend_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        friendList = view.findViewById(R.id.friend_list);
        LinearLayout addFriendLayout = view.findViewById(R.id.add_friend_layout);
        LinearLayout newFriendLayout = view.findViewById(R.id.new_friend_layout);
        LinearLayout groupListLayout = view.findViewById(R.id.group_list_layout);
        LinearLayout createGroupLayout = view.findViewById(R.id.create_group_layout);

        addFriendLayout.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                Intent intent = new Intent(getContext(), AddFriendActivity.class);
                startActivity(intent);
            }
        });

        newFriendLayout.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                Intent intent = new Intent(getContext(), NewFriendActivity.class);
                launcher.launch(intent);
            }
        });

        groupListLayout.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                Intent intent = new Intent(getContext(), GroupListActivity.class);
                startActivity(intent);
            }
        });

        createGroupLayout.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                Intent intent = new Intent(getContext(), AddGroupActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

        if (!hasInitData) {
            if (data != null) {
                initFriendListView(data.getGroupList());
                hasInitData = true;
            }
        }
    }

    public void refreshData(FriendListModel data) {
        this.data = data;
        updateView();
    }

    public void refreshDataByUser(UserInfo info) {
        if (data != null) {
            boolean hasChanged = false;
            if (StringUtil.isNotEmpty(data.getStarList())) {
                for (FriendModel model : data.getStarList()) {
                    hasChanged = updateUser(model, info);
                    if (hasChanged) {
                        break;
                    }
                }
            }

            if (StringUtil.isNotEmpty(data.getGroupList())) {
                for (GroupFriendModel groupFriendModel : data.getGroupList()) {
                    if (StringUtil.isNotEmpty(groupFriendModel.getItems())) {
                        boolean changed = false;
                        for (FriendModel model : groupFriendModel.getItems()) {
                            changed = updateUser(model, info);
                            if (changed) {
                                break;
                            }
                        }
                        if (changed) {
                            hasChanged = true;
                            break;
                        }
                    }
                }
            }

            if (hasChanged) {
                updateView();
            }
        }
    }

    private void initLauncher() {
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Log.i(TAG, "the result code is:" + result.getResultCode());
                int resultCode = result.getResultCode();
                if (resultCode != Activity.RESULT_OK) {
                    return;
                }
                Intent data = result.getData();
                if (data == null) {
                    return;
                }

                boolean needRefresh = data.getBooleanExtra("needRefresh", false);
                Log.i(TAG, "the needRefresh is:" + needRefresh);
                if (needRefresh) {
                    FragmentActivity activity = getActivity();
                    if (activity instanceof MainActivity) {
                        ((MainActivity) activity).refreshFriendList();
                    }
                }
            }
        });
    }

    private void updateView() {
        if (data == null) {
            return;
        }

        try {
            Activity activity = getActivity();
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initFriendListView(data.getGroupList());
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private boolean updateUser(FriendModel model, UserInfo info) {
        String userId = AppUtil.getTargetUserId(model.getId());
        if (userId.equals(info.getUserId())) {
            if (model.hasChanged(info)) {
                model.setName(info.getName());
                model.setPhoto(info.getPortraitUri().getPath());
                if (StringUtil.isEmpty(model.getRemark())) {
                    model.setFriendName(info.getName());
                }
                Log.i("ROC", "the model is:" + JsonUtil.toJson(model));
                return true;
            }
        }
        return false;
    }

    private void initFriendListView(List<GroupFriendModel> list) {
        FriendListExpandableListAdapter adapter;
        if (initList) {
            adapter = (FriendListExpandableListAdapter) friendList.getExpandableListAdapter();
            adapter.update(list);
            friendList.setAdapter(adapter);
        } else {
            adapter = new FriendListExpandableListAdapter(getContext(), list);
            adapter.setClickListener(new FriendListExpandableListAdapter.OnItemClickListener() {
                @Override
                public void onClick(FriendModel model) {
                    updateUser(model);

                    RouteUtils.routeToConversationActivity(getContext(), Conversation.ConversationType.PRIVATE, AppUtil.getTargetUserId(model.getId()));
                }
            });
            friendList.setAdapter(adapter);
            initList = true;
        }
        expandAll(adapter.getGroupCount());
    }

    private void updateUser(FriendModel model) {
        String userId = AppUtil.getTargetUserId(model.getId());
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(userId);
        if (Objects.isNull(userInfo)) {
            RongUserInfoManager.getInstance().refreshUserInfoCache(AppUtil.getUserInfo(model));
        } else {
            if (model.hasChanged(userInfo)) {
                RongUserInfoManager.getInstance().refreshUserInfoCache(AppUtil.getUserInfo(model));
            }
        }
    }

    private void expandAll(int maxIndex) {
        if (Objects.isNull(friendList)) {
            return;
        }
        for (int i = 0; i < maxIndex; i++) {
            friendList.expandGroup(i);
        }
    }
}